
from influxdb import InfluxDBClient

from base_db import Influxdb_info
from config import get_json_data, modify_json_data
import datetime
def runclish(user_name,clish):
    costtime = ''
    data = get_json_data(user_name)
    IP = data['IP']
    port = data['port']
    influxDB_name = data['influxDB_name']
    influxDB_table = data['influxDB_table']
    file = data["file"]
    db_info = Influxdb_info()
    password_db = db_info.get_influxDB_password()
    client = InfluxDBClient(IP, port, influxDB_name, password_db, influxDB_table, ssl=True)
    # client = InfluxDBClient(IP, port, influxDB_name, '', influxDB_table, ssl=True)
    sql = clish
    print(sql)
    try:
        start = datetime.datetime.now()
        print("【Info】 Start time of SQL begin to running is {}".format(start))
        res = client.query(
            sql,
            database=influxDB_table)
        end = datetime.datetime.now()
        print("【Info】 End time of SQL begin to running is {}".format(end))
        costtime = end -start
        print("【Info】 Cost time of SQL begin to running is {}".format(costtime))
    except Exception as e:
        print("【Error】 SQL can not run in this system")
        print(e)
        res = e
    if "influxdb.resultset.ResultSet" not in str(type(res)) :
        with open(file, "w", encoding='utf-8') as f:
            f.write(str(res))

    elif res:
        print(type(res))
        result = list(res)[0]
        # print(result)
        # print('1111111')
        with open(file, "w", encoding='utf-8') as f:
            for i in result:
                #添加的
                # print(i["Path"])
                # f.write(str(i["Path"]) + "\n")
                f.write(str(i) + "\n")
            # f.write(str(result)[0])
            f.write("[INFO] 数据个数： " + str(len(result)))
            print("[INFO] 数据个数： " + str(len(result)))
    else:
        with open(file, "w", encoding='utf-8') as f:
            f.write("[INFO] 查询数据个数： 0")
            print("[INFO] 查询数据个数： 0")

    client.close()
    return costtime
